<?php

namespace Icsoc\RecordingBundle\Controller;

use Icsoc\ExportLib\Col;
use Icsoc\ReportBundle\Controller\ReportController;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Class RecordController
 *
 * @package Icsoc\RecordingBundle\Controller
 */
class RecordController extends ReportController
{
    private $callType = array('1' => '呼出', '2' => '呼入'); //呼叫类型
    private $downs = array('0' => '未下载', '1' => '已下载'); //下载
    private $listens = array('0' => '未收听', '1' => '已收听'); //下载

    /**
     * 录音列表
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function recordListAction()
    {
        $em = $this->getDoctrine()->getManager();
        $vccId = $this->getUser()->getVccId();
        $isSpecial = $this->container->get("icsoc_core.common.class")->getIsAdmin();
        //$endType = $this->container->getParameter("end_type");
        $evaluates = $this->container->getParameter('EVALUATES');
        //$queues = $em->getRepository("IcsocSecurityBundle:WinQueue")->getQuesName($where, $options);
        $queues = $this->container->get('icsoc_data.model.queue')->getQueueNameKeyedByIdArray($vccId, true);
        $isEnableGroup = $this->getDoctrine()->getRepository("IcsocSecurityBundle:CcCcodConfigs")->isEnableGroup($vccId);
        /*获取所有业务组*/
        $groups = $em->getRepository("IcsocSecurityBundle:WinGroup")->getGroupsName($vccId);
        $options = array(
            'ag_num' => array('text' => 'Agent', 'type' => 2),
            'call_type' => array('text' => 'Call type', 'type' => 2, 'options' => $this->callType),
            'cus_phone' => array('text' => 'Cus Phone', 'type' => 1),
            'ag_phone' => array('text' => 'Agent Phone', 'type' => 1),
            'que_id' => array('text' => 'Queues', 'type' => 2, 'options' => $queues),
            //'end_result'=>array('text'=>'End Reason', 'type'=>2, 'options'=>$endType, 'all'=>''),
            'evaluates' => array('text' => 'End type', 'type' => 2, 'options' => $evaluates, 'all' => ''),
            'ssecs' => array('text' => 'When the length of more than', 'type' => 1),
            'esecs' => array('text' => 'When the length of less than', 'type' => 1),
            'serv_num' => array('text' => 'Server Num', 'type' => 1),
        );
        if ($isEnableGroup) {
            $options['group_id'] = array('text' => 'Business Group', 'type' => 2, 'options' => $groups);
        }
        $actionList = $this->getActionList();
        $actions = explode(',', $actionList);
//        $isBatchDown = ($actionList == 'all' || in_array('icsoc_recording_list_batch_down_data', $actions))
//            ? true : false;
        //录音收听
        $listenSound = ($actionList == 'all' || in_array('icsoc_recording_list_listen_sound', $actions)) ? true : false;
        //录音下载
        $downSound = ($actionList == 'all' || in_array('icsoc_recording_list_down_sound', $actions)) ? true : false;

        return $this->render("IcsocRecordingBundle:Record:index.html.twig", array(
            'date' => $this->getData(),
            'options' => $options,
            //'isBatchDown' => $isBatchDown,
            'isEnableGroup' => $isEnableGroup,
            'isSpecial' => $isSpecial,
            'listenSound' => $listenSound,
            'downSound' => $downSound,
        ));
    }

    /**
     * 获取录音数据
     *
     * @param Request $request
     *
     * @return JsonResponse|Response
     */
    public function recordListDataAction(Request $request)
    {
        $data = $request->get('param', '');
        //$forPageParam = $request->get('forPage', '');
        $data = html_entity_decode(urldecode($data));
        $page = $request->get('page', 1);
        $rows = $request->get('rows', 10);
        $sord = $request->get('sord', 'desc');
        $sidx = $request->get('sidx', 'id');
        $export = $request->get('export', '');
        $big = $request->get('big', false);
        $sum = $request->get('sum', false);

        $info = array(
            'export' => $export,
            'pagination' => array('rows' => $rows, 'page' => $page),
            'filter' => !empty($data) ? json_decode($data, true) : array(),
            'sort' => array('order' => $sord, 'field' => $sidx),
        );
        /*$list = $this->get('icsoc_data.model.record')->recordList(
            array(
                'vcc_code' => $this->getUser()->getVccCode(),
                'info' => json_encode($info),
                'forPageParam' => json_decode($forPageParam, true),
            )
        );*/

        $list = $this->get('icsoc_data.model.record')->getRecordListFromElasticsearch(
            array(
                'vcc_code' => $this->getUser()->getVccCode(),
                'info' => json_encode($info),
                'big' => $big,
            )
        );
        if ($sum == true) {
            return new JsonResponse(array('code' => 200, 'count' => $list['total']));
        }
        $vccId = $this->getVccId();
        $isEnableGroup = $this->getDoctrine()->getRepository("IcsocSecurityBundle:CcCcodConfigs")->isEnableGroup($vccId);
        /*获取所有业务组*/
        //$groups = $em->getRepository("IcsocSecurityBundle:WinGroup")->getGroupsName($vccId);
        /*if ($big == false && isset($list['code']) && $list['code'] == 200) {
            foreach ($list['data'] as $k => $v) {
                $list['data'][$k]['group_id'] = isset($groups[$v['group_id']]) ? $groups[$v['group_id']] : '';
            }
        }*/

        /** 导出功能 */
        if (!empty($export) && $list['code'] == 200) {
            /** @var  $title (导出字段) */
            $title = array(
                'ag_num' => array(
                    'title' => 'Agent Num',
                    'type' => Col::TYPE_STRING,
                ),
                'ag_name' => array(
                    'title' => 'Agent Name',
                    'type' => Col::TYPE_STRING,
                ),
                'que_name' => array(
                    'title' => 'Queue',
                    'type' => Col::TYPE_STRING,
                ),
                'call_type' => array(
                    'title' => 'Call type',
                    'type' => Col::TYPE_STRING,
                ),
                'serv_num' => array(
                    'title' => 'Relay number',
                    'type' => Col::TYPE_STRING,
                ),
                'ag_phone' => array(
                    'title' => 'Agent Phone',
                    'type' => Col::TYPE_STRING,
                ),
                'cus_phone' => array(
                    'title' => 'The customer number',
                    'type' => Col::TYPE_STRING,
                ),
                'start_time' => array(
                    'title' => 'Start Time',
                    'type' => Col::TYPE_STRING,
                    'filters' => array(
                        array(
                            'filter' => 'datetime',
                            'format' => 'Y-m-d H:i:s',
                        ),
                    ),
                ),
                'end_time' => array(
                    'title' => 'End time',
                    'type' => Col::TYPE_STRING,
                    'filters' => array(
                        array(
                            'filter' => 'datetime',
                            'format' => 'Y-m-d H:i:s',
                        ),
                    ),
                ),
                'conn_secs' => array(
                    'title' => 'The long recording time',
                    'type' => Col::TYPE_STRING,
                ),
                'evaluate' => array(
                    'title' => 'End type',
                    'type' => Col::TYPE_STRING,
                ),
            );
            if ($isEnableGroup) {
                $title = array(
                    'ag_num' => array(
                        'title' => 'Agent Num',
                        'type' => Col::TYPE_STRING,
                    ),
                    'ag_name' => array(
                        'title' => 'Agent Name',
                        'type' => Col::TYPE_STRING,
                    ),
                    'group_name' => array(
                        'title' => 'Business Group',
                        'type' => Col::TYPE_STRING,
                    ),
                    'que_name' => array(
                        'title' => 'Queue',
                        'type' => Col::TYPE_STRING,
                    ),
                    'call_type' => array(
                        'title' => 'Call type',
                        'type' => Col::TYPE_STRING,
                    ),
                    'serv_num' => array(
                        'title' => 'Relay number',
                        'type' => Col::TYPE_STRING,
                    ),
                    'ag_phone' => array(
                        'title' => 'Agent Phone',
                        'type' => Col::TYPE_STRING,
                    ),
                    'cus_phone' => array(
                        'title' => 'The customer number',
                        'type' => Col::TYPE_STRING,
                    ),
                    'start_time' => array(
                        'title' => 'Start Time',
                        'type' => Col::TYPE_STRING,
                        'filters' => array(
                            array(
                                'filter' => 'datetime',
                                'format' => 'Y-m-d H:i:s',
                            ),
                        ),
                    ),
                    'end_time' => array(
                        'title' => 'End time',
                        'type' => Col::TYPE_STRING,
                        'filters' => array(
                            array(
                                'filter' => 'datetime',
                                'format' => 'Y-m-d H:i:s',
                            ),
                        ),
                    ),
                    'conn_secs' => array(
                        'title' => 'The long recording time',
                        'type' => Col::TYPE_STRING,
                    ),
                    'evaluate' => array(
                        'title' => 'End type',
                        'type' => Col::TYPE_STRING,
                    ),
                );
            }
            if ($big == false) {
                switch ($export) {
                    case 'csv':
                        return $this->container->get('icsoc_data.model.batchExport')->exportCsv($title, $list['data']);
                    case 'excel':
                        return $this->container->get('icsoc_data.model.batchExport')->exportExcel($title, $list['data']);
                    default:
                        exit;
                }
            } else if ($big == true) {
                $type = array(
                    'evaluate' => 'enum',
                    'call_type' => 'enum',
                );
                $endResults['enum']['evaluate'] = $this->container->getParameter('EVALUATES');
                $endResults['enum']['call_type'][1] = '呼出';
                $endResults['enum']['call_type'][2] = '呼入';
                /** @var  $title (导出字段) */
                $newTitle = $this->get('icsoc_data.model.export')->getNewTitle($title, $type, $endResults);
                //新版异步导出
                $newData = array(
                    'es_search'=>json_encode($list['data']),
                    'mongo_coll' => 'win_agcdr',
                    'cols' =>json_encode($newTitle),
                );
                $re = $this->get('icsoc_data.model.export')->newRecord($export, $newData, '录音列表');

                return new JsonResponse($re);
            }
        }

        $result = array(
            'records' => isset($list['total']) ? $list['total'] : 0,
            'rows' => (isset($list['data']) && !empty($list['data'])) ? $list['data'] : array(),
            'total' => isset($list['totalPage']) ? $list['totalPage'] : 0,
            'page' => isset($list['page']) ? $list['page'] : $page,
        );

        return new JsonResponse($result);
    }

    /**
     * 留言列表
     *
     * @return Response
     */
    public function messageListAction()
    {
        $options = array(
            'caller' => array('text' => 'Calling number', 'type' => 1),
            'called' => array('text' => 'Called number', 'type' => 1),
            'listen_mark' => array(
                'text' => 'Whether to have to listen', 'type' => 2,
                'options' => $this->listens, 'selected' => '0',
            ),
            'down_mark' => array('text' => 'Whether it has been downloaded', 'type' => 2, 'options' => $this->downs),
            'ssecs' => array('text' => 'When the length of more than', 'type' => 1),
            'esecs' => array('text' => 'When the length of less than', 'type' => 1),
        );

        return $this->render("IcsocRecordingBundle:Record:message.html.twig", array(
            'date' => $this->getData(),
            'options' => $options,
        ));
    }

    /**
     * 留言列表数据
     *
     * @param Request $request
     *
     * @return JsonResponse
     */
    public function messageListDataAction(Request $request)
    {
        $data = $request->get('param', '');
        $data = html_entity_decode(urldecode($data));
        $page = $request->get('page', 1);
        $rows = $request->get('rows', 10);
        $sord = $request->get('sord', 'desc');
        $sidx = $request->get('sidx', 'id');
        $export = $request->get('export', '');
        $big = $request->get('big', false);         //判断用那种方式导出
        $sum = $request->get('sum', false);         //判断只查询数量的情况

        $info = array(
            'export' => $export,
            'pagination' => array('rows' => $rows, 'page' => $page),
            'filter' => !empty($data) ? json_decode($data, true) : array(),
            'sort' => array('order' => $sord, 'field' => $sidx),
        );
        $list = $this->get('icsoc_data.model.record')->voiceList(
            array(
                'vcc_code' => $this->getUser()->getVccCode(),
                'info' => json_encode($info),
                'big' => $big,
            )
        );
        if ($sum == true) {
            return new JsonResponse(array('code' => 200, 'count' => $list['total']));
        }
        /** 导出功能 */
        if (!empty($export) && $list['code'] == 200) {
            /** @var  $title (导出字段) */
            $title = array(
                'caller' => array(
                    'title' => 'Caller',
                    'type' => Col::TYPE_STRING,
                ),
                'called' => array(
                    'title' => 'Called',
                    'type' => Col::TYPE_STRING,
                ),
                'start_time' => array(
                    'title' => 'Message time',
                    'type' => Col::TYPE_STRING,
                    'filters' => array(
                        array(
                            'filter' => 'datetime',
                            'format' => 'Y-m-d H:i:s',
                        ),
                    ),
                ),
                'rec_secs' => array(
                    'title' => 'Message length (s)',
                    'type' => Col::TYPE_STRING,
                ),
                'listen_mark' => array(
                    'title' => 'Whether to have to listen',
                    'type' => Col::TYPE_STRING,
                ),
                'down_mark' => array(
                    'title' => 'Whether it has been downloaded',
                    'type' => Col::TYPE_STRING,
                ),
            );
            if ($big == false) {
                switch ($export) {
                    case 'csv':
                        return $this->container->get('icsoc_data.model.batchExport')->exportCsv($title, $list['data']);
                    case 'excel':
                        return $this->container->get('icsoc_data.model.batchExport')->exportExcel($title, $list['data']);
                    default:
                        exit;
                }
            } else if ($big == true) {
                $vccId = $this->getVccId();
                $type = array(
                    'start_time' => 'datetime',
                    'listen_mark' => array('enum' => array('unset')),
                    'down_mark' => array('enum' => array('unset')),
                );
                $endResults['enum']['listen_mark'][1] = '已收听';
                $endResults['enum']['listen_mark']['unset'] = '未收听';
                $endResults['enum']['down_mark'][1] = '已下载';
                $endResults['enum']['down_mark']['unset'] = '未下载';
                /** @var  $title (导出字段) */
                $newTitle = $this->get('icsoc_data.model.export')->getOldNewTitle($title, $export, $type, $endResults);
                $newData = array(
                    'vcc_id' => $vccId,
                    'sql' => $list['sql'],
                    'datacount' => $list['total'],
                    'cols' => json_encode($newTitle),
                );
                $re = $this->get('icsoc_data.model.export')->record($export, $newData, '留言列表');

                return new JsonResponse($re);
            }
        }

        $result = array(
            'records' => isset($list['total']) ? $list['total'] : 0,
            'rows' => (isset($list['data']) && !empty($list['data'])) ? $list['data'] : array(),
            'total' => isset($list['totalPage']) ? $list['totalPage'] : 0,
            'page' => $page,
        );

        return new JsonResponse($result);
    }

    /**
     * 批量下载；
     *
     * @param Request $request
     *
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
     */
    public function batchDownDataAction(Request $request)
    {
        $filter = $request->get("filter");
        $isAll = $request->get("isall", '');
        $ids = $request->get("ids", '');
        $filter = !empty($filter) ? json_decode($filter, true) : array();
        $info = array(
            'pagination' => array('rows' => 10000, 'page' => 1), //最大一百万条；ads最大10000;
        );
        if ($isAll == 1) {
            //全选；
            $isCancel = $request->get("iscancelIds");
            if (!empty($isCancel)) {
                $cancel = explode(",", $isCancel);
                $cancel = array_unique($cancel);
                $filter['notid'] = implode(',', $cancel);
            }
        } elseif ($isAll == 0 && !empty($ids)) {
            $filter['id'] = $ids;
        }
        $info['filter'] = $filter;
        $vccCode = $this->getUser()->getVccCode();
        $file = $this->get('icsoc_data.model.record')
            ->zipDownRecord(array('vcc_code' => $vccCode, 'info' => json_encode($info)));
        if (is_array($file)) {
            $data = array(
                'data' => array(
                    'msg_detail' => $file['message'],
                    'type' => 'danger',
                    'link' => array(
                        array(
                            'text' => $this->get('translator')->trans('The evaluate list'),
                            'href' => $this->generateUrl('icsoc_evaluate_detail'),
                        ),
                    ),
                ),
            );

            return $this->redirect($this->generateUrl('icsoc_ui_message', $data));
        } else {
            $response = new BinaryFileResponse($file);
            $response->setContentDisposition('attachment', basename($file));
            $response->deleteFileAfterSend(true);//下载完成后删除源文件；

            return $response;
        }
    }

    /**
     * 新批量下载；
     *
     * @param Request $request
     *
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
     */
    public function newBatchDownDataAction(Request $request)
    {
        $filter = $request->get("filter");
        $isAll = $request->get("isall", '');
        $ids = $request->get("ids", '');
        $filter = !empty($filter) ? json_decode($filter, true) : array();
        $info = array(
            'pagination' => array('rows' => 1000, 'page' => 1), //最大一百万条；ads最大10000;
        );
        if ($isAll == 1) {
            //全选；
            $isCancel = $request->get("iscancelIds");
            if (!empty($isCancel)) {
                $cancel = explode(",", $isCancel);
                $cancel = array_unique($cancel);
                $filter['notid'] = implode(',', $cancel);
            }
        } elseif ($isAll == 0 && !empty($ids)) {
            $filter['id'] = $ids;
        }
        $startTime = strtotime($filter['start_time']);
        $todayStartTime = strtotime(date("Y-m-d")." 00:00:00");
        if ($startTime < $todayStartTime) {
            $filter['start_time'] = date("Y-m-d")." 00:00:00";
        }
        $info['filter'] = $filter;
        $vccCode = $this->getUser()->getVccCode();
        $file = $this->get('icsoc_data.model.record')
            ->manyDownRecord(array('vcc_code' => $vccCode, 'info' => json_encode($info)));

        if ($file['code'] != 200) {
            $data = array(
                'data' => array(
                    'msg_detail' => $file['message'],
                    'type' => 'danger',
                    'link' => array(
                        array(
                            'text' => $this->get('translator')->trans('The recording list'),
                            'href' => $this->generateUrl('icsoc_recording_list'),
                        ),
                    ),
                ),
            );

            return $this->redirect($this->generateUrl('icsoc_ui_message', $data));
        } else {
            $response = new BinaryFileResponse($file['url']);
            $response->setContentDisposition('attachment', basename($file['url']));
            $response->deleteFileAfterSend(true);//下载完成后删除源文件；

            return $response;
        }
    }

    /**
     * 播放录音或留言；
     *
     * @param Request $request
     *
     * @return Response
     */
    public function playAction(Request $request)
    {
        $id = $request->get('id', '');
        $callId = $request->get('callid', '');
        $agCdrId = $request->get('agcdr_id', '');
        $flag = $request->get('flag', 1);
        $remark = $request->get('mark', 1);
        $vccCode = $this->getUser()->getVccCode();

        //处理callID
        $callId = $this->container
            ->get('icsoc_data.model.report')
            ->processCallId($callId);

        $info = $this->get('icsoc_data.model.record')
            ->getSoundInfo(
                array(
                    'vcc_code' => $vccCode,
                    'id' => $id,
                    'callid' => $callId,
                    'agcdr_id' => $agCdrId,
                    'flag' => $flag,
                    'remark' => $remark,
                )
            );
        $recordAddress = isset($info['address']) ? $info['address'] : '';

        if (empty($recordAddress)) {
            return new JsonResponse(array('err' => true));
        }

        $recordPrefixs = $this->container->getParameter('record_prefix');
        $prefix = '';
        foreach ($recordPrefixs as $k => $r) {
            if (strpos($recordAddress, $k) === 0) {
                $prefix = $r;
                $recordAddress = str_replace($k, '', $recordAddress);
                break;
            }
        }

        if (empty($prefix)) {
            return new JsonResponse(array('err' => true));
        }
        $mark = $flag == 1 ? 'voicemail' : 'call';//标记是
        $baseUrl = $this->container->getParameter('record_oss_url');
        $url = $baseUrl.DIRECTORY_SEPARATOR.$prefix.DIRECTORY_SEPARATOR.$mark.DIRECTORY_SEPARATOR.$recordAddress;

        return new JsonResponse(array('err' => false, 'url' => $url));
        /*
        $recordBackupAddress = '/recordbak'.substr($recordAddress, 7);

        if (file_exists($recordAddress)) {
            return new Response(@file_get_contents($recordAddress), 200, array(
                'Pragma' => 'Public',
                'Expires' => 0,
                'Cache-Component' => 'must-revalidate, post-check=0, pre-check=0',
                'Content-type' => 'audio/x-wav',
                'Content-Length' => filesize($recordAddress),
                'Content-Transfer-Encoding' => 'binary',
                'Accept-Ranges' => 'bytes',
                'Content-Disposition' => 'attachment;filename='.basename($recordAddress)
            ));
        } elseif (file_exists($recordBackupAddress)) {
            return new Response(@file_get_contents($recordBackupAddress), 200, array(
                'Pragma' => 'Public',
                'Expires' => 0,
                'Cache-Component' => 'must-revalidate, post-check=0, pre-check=0',
                'Content-type' => 'audio/x-wav',
                'Content-Length' => filesize($recordBackupAddress),
                'Content-Transfer-Encoding' => 'binary',
                'Accept-Ranges' => 'bytes',
                'Content-Disposition' => 'attachment;filename='.basename($recordBackupAddress)
            ));
        } else {
            return new Response("语音文件不存在");
        }*/
    }
}
